import * as SocketIO from 'socket.io';
import * as events from 'events';
import * as http from 'http';
import * as redis from 'redis';
var uid = require('uid');


export default class WebClient extends events.EventEmitter {
    constructor(public socket: SocketIO.Socket) {
        super();
        this._registerEvent();
    }

    public name: string = uid(20);

    public userName: string = '';

    protected _registerEvent() {
        this.socket.on('disconnect', () => {
            this.emit('disconnect');
        });
        this.socket.on('notify', () => {
            this.broadcastNotificationToOthers();
        });
        this.socket.on('register', (name) => {//用户注册自己的名字
            this.userName = name;
        });
    }

    /** 触发新消息，广播到其他用户那边去，其他网页用户收到该消息的话应该从服务器拉取未读的消息，附加到现有的消息里去 */
    public broadcastNotificationToOthers(): void {
        if (this.userName) {
            this.emit('notifyOthers');
            this.socket.broadcast.emit('notify');
        }
    }
}

